﻿using System.Web.Mvc;
using BLL.Enum;
using BLL.Installer;
using BLL.Interface.Base;
using BLL.Interface.User;

namespace WayCloud.Controllers.Account
{
    public class AccountController : Controller
    {
        public static string StartPage
        {
            get { return "~/apply/"; }
        }

        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                return Redirect(StartPage);
            }
            return View("Login");
        }

        [HttpGet]
        public ActionResult ValidateCode()
        {
            IValidateCode validateCodeManager = ContainerHelper.Instance.Container.Resolve<IValidateCode>();
            var code = validateCodeManager.CreateCode();
            var image = validateCodeManager.CreateImage(code);
            return File(image, @"image/gif");
        }

        public ActionResult CheckLogin(BLL.Model.Base.Login loginInfo)
        {
            if (!ModelState.IsValid)
            {
                return RedirectToAction("Index");
            }
            ILoginHelper loginHelperManager = ContainerHelper.Instance.Container.Resolve<ILoginHelper>();
            string sessionId;
            var result = loginHelperManager.Login(() =>
                                                      {
                                                          IUserInfo userInfoManager =
                                                              ContainerHelper.Instance.Container.Resolve<IUserInfo>();
                                                          return userInfoManager.CheckUser(loginInfo.UserName,
                                                                                           loginInfo.Password);
                                                      }, out sessionId);
            if (result)
            {
                Session[SessionParameterEnum.CurrentUserId] = sessionId;
                return Redirect(StartPage);
            }
            ViewBag.ErrorMessage = "用户名或密码错误！";
            return View("Login", loginInfo);
        }

        [HttpGet, Authorize]
        public ActionResult LogOut()
        {
            ILoginHelper loginHelperManager = ContainerHelper.Instance.Container.Resolve<ILoginHelper>();
            loginHelperManager.LogOut(() =>
                                          {
                                              var user = this.GetLoginUser();
                                              Session[SessionParameterEnum.CurrentUserId] = null;
                                              return user;
                                          });
            return Redirect("~/account/");
        }

    }
}
